package org.shiro.demo.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.joda.time.Seconds;
import org.shiro.demo.dao.util.QueryCondition;
import org.shiro.demo.entity.Phone;
import org.shiro.demo.entity.ResponseResult;
import org.shiro.demo.entity.User;
import org.shiro.demo.entity.WeixinOpen;
import org.shiro.demo.service.IBaseService;
import org.shiro.demo.service.IUserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.utils.CommonUtil;

/**
 * 用户绑定微信 接口
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/weixin")
public class WeixinBindController {

	@Resource(name = "userService")
	private IUserService userService;

	@Resource(name = "baseService")
	private IBaseService baseService;

	/**
	 * 为了 绑定 用户的微信号码
	 * 
	 * 参数：来自微信的code
	 * 
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/barcode", method = RequestMethod.GET)
	public @ResponseBody Object barcode(String code) {
		ResponseResult rr = new ResponseResult(0, "", null);
		if (StringUtils.isEmpty(code)) {
			rr.setInfo("code为空");
			return rr;
		}
		try {

			// 访问 微信平台得到openid
			// 商户相关资料

			// 得到openid
			String openId = getOpenId(code);
			if (StringUtils.isEmpty(openId)) {
				rr.setInfo("openid为空，请稍后再试");
				return rr;
			}
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			list.add(new QueryCondition("openid", QueryCondition.EQ, openId));
			WeixinOpen weixinopen = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list);
			if (weixinopen != null) {
				// 生成 条形码。

				Random r = new Random();
				String abcdefg = "abcdefghijklmnopqrstuvwxyz";
				String randomLetter = "";
				int num = r.nextInt(abcdefg.length());
				char c = abcdefg.charAt(num);

				String str = String.format("%07d", new Object[] { Integer.valueOf(weixinopen.getUserId()) });
				str = str.replace("0", String.valueOf(c));
				StringBuilder sb = new StringBuilder();
				sb.append("ebo");
				sb.append(str);

				sb.append((int) (Math.random() * 899.0D + 100.0D));
				Phone phone = baseService.getById(Phone.class, weixinopen.getPhone());
				String barcode = sb.toString();
				if (phone != null) {
					// 更新
					phone.setBarcode(barcode);
					phone.setBarcodeTime(new Date());

				} else {
					// 添加
					phone = new Phone();
					phone.setNum(weixinopen.getPhone());
					phone.setBarcode(barcode);
					phone.setBarcodeTime(new Date());

				}
				baseService.update(phone);

				return new ResponseResult(1, "成功获取 条形码", barcode);
			} else {
				// 该 微信号 没有绑定
				return new ResponseResult(0, "该 微信号 没有绑定", null);
			}

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("系统内部出错");
			return rr;
		}

	}

	@RequestMapping(value = "/bind", method = RequestMethod.GET)
	@RequiresAuthentication
	@RequiresRoles("customer")
	public String bind(String code) {
		ResponseResult rr = new ResponseResult();
		if (StringUtils.isEmpty(code)) {
			rr.setInfo("code为空");
			return "redirect:/html/code128.html?barcode=success";
		}
		try {

			// 访问 微信平台得到openid
			// 商户相关资料

			// 得到openid
			String openId = getOpenId(code);
			if (StringUtils.isEmpty(openId)) {
				rr.setInfo("openid为空，请稍后再试");
				return "redirect:/html/code128.html?barcode=success";
			}
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			list.add(new QueryCondition("openid", QueryCondition.EQ, openId));
			WeixinOpen weixinopen = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list);
			if (weixinopen != null) {
				rr.setInfo("微信已绑定");// 一个微信 只能绑定一只手机
				return "redirect:/html/code128.html?barcode=success";
			} else {

				User user = (User) SecurityUtils.getSubject().getPrincipal();
				List<QueryCondition> list2 = new ArrayList<QueryCondition>();
				list2.add(new QueryCondition("phone", QueryCondition.EQ, user.getPhone()));
				WeixinOpen weixinopen2 = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list2);
				if (weixinopen2 == null) {// 一只手机只能有一个微信
					weixinopen = new WeixinOpen();
					weixinopen.setBindTime(new Date());
					weixinopen.setOpenid(openId);
					weixinopen.setPhone(user.getPhone());
					weixinopen.setUserId(user.getId());
					baseService.save(weixinopen);
					rr.setInfo("绑定成功");
					rr.setCode(1);
				}
				return "redirect:/html/code128.html?barcode=success";
			}
		} catch (Exception e) {
			e.printStackTrace();
			rr.setInfo("内部出错");
			return "redirect:/html/code128.html?barcode=success";
		}
	}

	@RequestMapping(value = "/unbind", method = RequestMethod.GET)
	@RequiresAuthentication
	public String unbind(String code) {
		ResponseResult rr = new ResponseResult();
		if (StringUtils.isEmpty(code)) {
			rr.setInfo("code为空");
			return "redirect:/html/wechat-login.html";
		}
		try {

			// 访问 微信平台得到openid
			// 商户相关资料

			// 得到openid
			String openId = getOpenId(code);
			if (StringUtils.isEmpty(openId)) {
				rr.setInfo("openid为空，请稍后再试");
				return "redirect:/html/wechat-login.html";
			}
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			list.add(new QueryCondition("openid", QueryCondition.EQ, openId));
			WeixinOpen weixinopen = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list);
			if (weixinopen != null) {
				rr.setInfo("微信已绑定。可以解绑");
				baseService.delete(WeixinOpen.class, weixinopen.getPhone());// 一个微信
																			// 只能绑定一只手机
				return "redirect:/html/code128.html?barcode=success";
			} else {

				rr.setInfo("微信已绑定。可以解绑");
				return "redirect:/html/code128.html?barcode=success";
			}
		} catch (Exception e) {
			e.printStackTrace();
			rr.setInfo("内部出错");
			return "redirect:/html/wechat-login.html";
		}
	}

	private String getOpenId(String code) {
		String appid = "wx1d8e9a967a8c62bd";
		String appsecret = "c687ad8537af8d8e1ca2fc573095a426";
		String partner = "1227994702";
		String partnerkey = "BdplgSwZUTqFBXdCikJB91kx6aCiIF3O";

		String openId = "";
		String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code";

		JSONObject jsonObject = CommonUtil.httpsRequest(URL, "GET", null);
		if (null != jsonObject) {
			openId = jsonObject.getString("openid");
			return openId;
		} else {
			return null;
		}
	}

	private int expried = 10; // 过期时间 （10分钟）

	private boolean isExpired(Date date) {
		DateTime from = new DateTime(date);
		DateTime to = new DateTime(new Date());
		if (Minutes.minutesBetween(from, to).getMinutes() > expried) {
			return true;// 过期了
		}
		return false;
	}

	private int repeateTime = 30; // 30秒 发一次

	private boolean isRepeate(Date date) {
		DateTime from = new DateTime(date);
		DateTime to = new DateTime(new Date());
		// 间隔 小于 30秒
		if (Seconds.secondsBetween(from, to).getSeconds() < repeateTime) {
			return true;// 重复了
		}
		return false;
	}

	/**
	 * 读取 用户信息
	 * 
	 * 参数：来自微信的code
	 * 
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/info", method = RequestMethod.GET)
	public @ResponseBody Object info(String openId) {
		ResponseResult rr = new ResponseResult(0, "", null);
		if (StringUtils.isEmpty(openId)) {
			rr.setInfo("code为空");
			return rr;
		}
		try {
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			list.add(new QueryCondition("openid", QueryCondition.EQ, openId));
			WeixinOpen weixinopen = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list);
			if (weixinopen != null) {
				List<QueryCondition> list1 = new ArrayList<QueryCondition>();
				list1.add(new QueryCondition("phone", QueryCondition.EQ, weixinopen.getPhone()));
				User user = (User) baseService.getSingleResult(User.class, list1);
				user.setPassword(null);
				return new ResponseResult(1, "成功获取  个人信息", user);
			} else {
				// 该 微信号 没有绑定
				return new ResponseResult(0, "该 微信号 没有绑定", null);
			}

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("系统内部出错");
			return rr;
		}

	}

	/**
	 * 读取 用户信息的openid
	 * 
	 * 参数：来自微信的code
	 * 
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/openid", method = RequestMethod.GET)
	public @ResponseBody Object openid(String code) {
		ResponseResult rr = new ResponseResult(0, "", null);
		if (StringUtils.isEmpty(code)) {
			rr.setInfo("code为空");
			return rr;
		}
		try {
			// 访问 微信平台得到openid
			// 商户相关资料

			// 得到openid
			String openId = getOpenId(code);
			if (StringUtils.isEmpty(openId)) {
				rr.setInfo("openid为空，请稍后再试");
				rr.setCode(0);
				return rr;
			} else {
				List<QueryCondition> list = new ArrayList<QueryCondition>();
				list.add(new QueryCondition("openid", QueryCondition.EQ, openId));
				WeixinOpen weixinopen = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list);
				if (weixinopen != null) {
					rr.setInfo("success");
					rr.setCode(1);
					rr.setObject(openId);
					return rr;
				} else {
					rr.setInfo("微信没有绑定任何手机号");
					rr.setCode(0);
					return rr;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("找不到对应的微信号");
			return rr;
		}

	}

	/**
	 * 不需要 code
	 * 
	 * 参数：来自微信的
	 * 
	 * @param session
	 * @param request
	 * @param reponse
	 * @return
	 */
	@RequestMapping(value = "/barcode2", method = RequestMethod.GET)
	public @ResponseBody Object barcode2(String openId) {
		ResponseResult rr = new ResponseResult(0, "", null);
		if (StringUtils.isEmpty(openId)) {
			rr.setInfo("code为空");
			return rr;
		}
		try {
			List<QueryCondition> list = new ArrayList<QueryCondition>();
			list.add(new QueryCondition("openid", QueryCondition.EQ, openId));
			WeixinOpen weixinopen = (WeixinOpen) baseService.getSingleResult(WeixinOpen.class, list);
			if (weixinopen != null) {
				// 生成 条形码。

				Random r = new Random();
				String abcdefg = "abcdefghijklmnopqrstuvwxyz";
				String randomLetter = "";
				int num = r.nextInt(abcdefg.length());
				char c = abcdefg.charAt(num);

				String str = String.format("%07d", new Object[] { Integer.valueOf(weixinopen.getUserId()) });
				str = str.replace("0", String.valueOf(c));
				StringBuilder sb = new StringBuilder();
				sb.append("ebo");
				sb.append(str);

				sb.append((int) (Math.random() * 899.0D + 100.0D));
				Phone phone = baseService.getById(Phone.class, weixinopen.getPhone());
				String barcode = sb.toString();
				if (phone != null) {
					// 更新
					phone.setBarcode(barcode);
					phone.setBarcodeTime(new Date());

				} else {
					// 添加
					phone = new Phone();
					phone.setNum(weixinopen.getPhone());
					phone.setBarcode(barcode);
					phone.setBarcodeTime(new Date());

				}
				baseService.update(phone);

				return new ResponseResult(1, "成功获取 条形码", barcode);
			} else {
				// 该 微信号 没有绑定
				return new ResponseResult(0, "该 微信号 没有绑定", null);
			}

		} catch (Exception e) {
			e.printStackTrace();
			rr.setCode(0);
			rr.setInfo("系统内部出错");
			return rr;
		}

	}
}
